$(document).ready(function() {

    (function($) {

        var cart = {
            init: function(){
                //show item
                $('.shop_item_image,.quick_view').fancybox({
                    fitToView       : false,
                    width           : 740,
                    height          : 590,
                    href            : '#addCart',
                    autoSize        : false,
                    closeClick      : false,
                    openEffect      : 'elastic',
                    closeEffect     : 'elastic',
                    closeBtn        : false,
                    padding         : 0,
                    beforeLoad      : function(){
                        cart.showItem($(this.element));
                    }
                });

                //add item via full info
                $('.full_item_add .add_to_cart_from_full').live('click',this.addItemViaFull);

                //add item simple
                $('.add_to_cart').live('click',this.addItem);

                //update cart
                $(".shop_cart_count_items,.shop_cart_image").fancybox({
                    fitToView       : false,
                    width           : 740,
                    height          : 590,
                    href            : '#cartContent',
                    autoSize        : false,
                    closeClick      : false,
                    openEffect      : 'elastic',
                    closeEffect     : 'elastic',
                    closeBtn        : false,
                    padding         : 0,
                    beforeLoad      : function(){
                        cart.updateCart();
                    }
                });

                //show image on keypressing
                $('.cart_item_quantity').live('keypress',function(e){
                    $(this).find('img').css('display','inline');
                });

                //change quantity
                $('.cart_item_quantity img').live('click',this.changeQuantity);

                //delete item from cart
                $('.cart_item_remove_btn').live('click',this.deleteItem);

                //back to shop
                $('.cart_footer_left a').live('click',this.closeCart);

                //proceed to checkout
                $('.proceed_checkout').live('click',this.proceedCheckout);

            },
            showItem: function(element){
                var itemId = element.parent().find('.add_to_cart').data('id'),
                    content = $('#addCart');

                $.ajax({
                    type        : 'POST',
                    dataType    : 'json',
                    url         : '/cart/add/get/' + itemId + '/',
                    success     : function(data){
                        if(data.success){
                            var item = data.success;
                            content.empty();
                            cont = '<div class="full_item_wrapper">';                               //wrapper start
                            cont+= '<div class="full_item_header">Product Card</div>';              //header
                            cont+= '<div class="full_item_main">';                                      //main block start
                            cont+= '<div class="full_item_main_left">';                             //main block left part start

                            cont+= '<div class="zoom_wrapper">';
                            cont+= '<a class="cloud-zoom" href="'+item.zoom_img_url+'" rel="zoomWidth:350, zoomHeight:400, position:\'zoom\'">'
                            cont+= '<img src="'+item.big_img_url+'"/></a>';                             //big_img
                            cont+= '</div>';


                            cont+= '</div>';                                                        //main block left part end

                            cont+= '<div class="full_item_main_right">';                            //main block right start
                            cont+= '<div id="zoom"></div>';
                            cont+= '<div class="full_item_name">'+item.name+'</div>';               //item name

                            cont+= '<div class="full_text_wrapper">';                               //text wrapper start
                            cont+= '<div class="full_item_text">'+item.fulltext+'</div>';           //item text

                            cont+= '<div class="full_item_price">Price: <span>$ '+item.price+'</span></div>';//item price
                            cont+= '</div>';                                                        //text wrapper end
                            cont+= '<div class="full_item_quantity"><span>Quantity: </span>';                              //item quantity start
                            cont+= '<input type="text" value="1"/>'; //select quantity
                            cont+= '</div>';                                                        //item quantity end
                            cont+= '<div class="full_item_add"><div class="add_to_cart_from_full" data-id="'+itemId+'"></div></div>';//item add to cart
                            cont+= '</div>';                                                        //main block right end
                            cont+= '</div>';                                                        //main block end
                            cont+= '<div class="full_item_bottom"></div>';                          //bottom

                            cont+= '</div>';                                                        //wrapper end
                            cont+= '<script type="text/javascript">jQuery(".cloud-zoom").CloudZoom();</script>';
                            content.html(cont);

                        }

                    }
                });
            },
            addItemViaFull : function(){
                var id = $(this).data('id'),
                    quantity = $(this).parent().parent().find('.full_item_quantity input').val(),
                    content = $(this).parent();
                cart.loader(content,'show',-40,13);
                $.ajax({
                    type    : 'POST',
                    url: '/cart/add/set/' + id + '/',
                    dataType: 'json',
                    data    : {'id' : id, 'quantity' : quantity },
                    success: function(data) {
                        cart.loader(content,'hide');
                        if (data.success) {

                            $('.shop_cart_count_items').text(data.success);
                        } else {
                            alert(data.errors);
                            $('.shop_cart_count_items').text(data.eRquantity);
                        }
                        $.fancybox.close();
                    },
                    error: function() {
                        $('#response').html('Something went wrong. Refresh page and try again.');
                    }
                });
                return false;
            },
            addItem : function(){
                var id = $(this).data('id'),
                    imgblock = $(this).parent().parent().parent().find('.shop_item_image'),
                    content = $(this).parent().parent().parent().find('.shop_item_image');

                imgblock.animate({
                    opacity : 0.3
                },500);

                cart.loader(content, 'show');

                $.ajax({
                    type    : 'POST',
                    url: '/cart/add/set/' + id + '/',
                    dataType: 'json',
                    data    : {'id' : id },
                    success: function(data) {
                        cart.loader(content, 'hide');
                        imgblock.animate({
                            opacity : 1
                        },1000);
                        if (data.success) {

                            $('.shop_cart_count_items').text(data.success);
                        } else {
                            alert(data.errors);
                            $('.shop_cart_count_items').text(data.eRquantity);
                        }
                    },
                    error: function() {
                        $('#response').html('Something went wrong. Refresh page and try again.');
                    }
                });
                return false;

            },
            updateCart: function(){
                $('#cartContent').empty();

                $.ajax({
                    type: 'POST',
                    url: '/cart/cart/',
                    success: function(msg) {
                        $('#cartContent').html(msg).hide().fadeIn(300);
                    }
                });
            },
            renewCart: function(){
                var content = $('#cartContent');

                $.ajax({
                    type: 'POST',
                    url: '/cart/cartUpdate/',
                    dataType: 'json',
                    success: function(data) {
                        if(data.quant >99) {
                            var quantity = '99+';
                        }
                        else{
                            var quantity = data.quant;
                        }
                        $('.shop_cart_count_items').text(quantity);
                        $('.cart_item').each(function(){
                            var subtotal = $(this).find('.cart_item_subtotal');
                            var id = $(this).attr('data-id');
                            var cartTotal = $('.cart_total span');
                            $.each(data.items, function(key,value) {
                                if(id == value['id'])
                                {
                                    subtotal.text('$ ' + value['price']*value['quantity']);
                                    cartTotal.text('$ ' + data.total);
                                }
                            });

                        })

                    },
                    complete:   function(){
                        cart.loader(content.parent(), 'hide');
                    }
                });
            },
            changeQuantity: function(){
                var quantity = $(this).parent().find('input').attr('value'),
                    id = $(this).parent().parent().find('.cart_item_remove span').attr('id'),
                    content = $(this).parent().parent();

                cart.loader(content, 'show',369,5);

                $.ajax({
                    type    :   'POST',
                    url     :   '/cart/quantity/',
                    dataType :  'json',
                    data    :   {'quantity' : quantity,'id' :id},
                    success :   function(data)
                    {
                        cart.renewCart();
                    },

                    error   :   function(msg)
                    {alert('not changed');}
                    ,
                    complete :  function(){
                        cart.loader(content, 'hide');
                    }

                });
                $(this).hide();
            },
            deleteItem: function(){
                var count = $('#shop_cart_count_items').text(),
                    removeId = $(this).attr('id'),
                    test =$(this).parent().parent(),
                    content = $(this).parent().parent();
                cart.loader(content, 'show');


                $.ajax({
                    type    :   'POST',
                    url     :   '/cart/cartDeleteItem/',
                    dataType :  'json',
                    data    :   {'id' : removeId},
                    success :   function(data)
                    {
                        $('.shop_cart_count_items').text(data.quant);
                        test.slideUp();

                        $('.cart_total span').text(data.total);

                    },
                    error   :   function(msg)
                    {alert('not deleted');},
                    complete :  function(){
                        cart.loader(content, 'hide');
                    }

                });
            },
            closeCart: function(){
                $.fancybox.close();
            },
            proceedCheckout: function(){
                window.location.href = "/commerce/checkout/";
            },
            loader: function($this, action,coordX,coordY) {
                var loader = new Image();
                loader.src = '/images/loader.gif';

                switch(action) {
                    case 'show':
                        if($this.children('.loader').length == 0) {
                            var wBlock = $this.width();
                            var hBlock = $this.height();

                            var coordX = coordX || false,
                                coordY = coordY || false;

                            var c = '<div class="loader" style="position: absolute; display: none; opacity: 0.8"></div>';
                            $this.append(c);
                            var newLoader = new Image();
                            newLoader.src = loader.src;

                            $this.children('.loader').append(newLoader);

                            if(coordX === false || coordY === false){
                                $this.children('.loader').css({
                                    'top': (hBlock-newLoader.height > 0) ? (hBlock-newLoader.height)/2 : 0,
                                    'left': (wBlock-newLoader.width > 0) ? (wBlock-newLoader.width)/2 : 0
                                }).fadeTo(100, 1);
                            }
                            else{
                                $this.children('.loader').css({
                                    'top'   : coordY,
                                    'left'  : coordX
                                }).fadeTo(100,1);
                            }
                        }
                        break;
                    case 'hide':
                        $this.children('.loader').stop().fadeOut(100, function() {
                            $(this).remove();
                        });
                        break;
                }
            }
        }

        cart.init();

    })(jQuery);

});